/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package cassandrawindow;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class HandleBalanceAndPromotionCPM {

    public static long checkDateDomainDate = 0;
    
    public void handleData() throws ParseException, InterruptedException
    {
        long first_time = System.currentTimeMillis();
        StringBuilder sb = new StringBuilder();
        //String currentDate = handleDate();
        String currentDate = HandleDataTableDomainDate.handleDate();//2012-07-24
        //String currentDate = "2013-08-01";
        /*
         * Lay tat ca nhung user active va tai khoan chinh ,tai khoan khuyen mai :getAllUserActive
         * lay tat ca nhung campaignid va userid lien quan :getCampaignAndUserid
         * Lay tien theo banner va domain :getMoneyByCampaignIdAndDomain
        */
        MysqlDataManager mysql = new MysqlDataManager();
        MysqlDataManagerMain mysqlMain = new MysqlDataManagerMain();
        
        //lay user active ,tai khoan khuyen mai,tai khoan chinh
        Map<Integer, String> allUsers = new HashMap<>();
        allUsers = mysqlMain.getAllUserActiveCPM();

        //lay tat ca nhung groupid la noi bo hay doi tac
        //groupid :1 la noi bo
        //gourpid :2 la khach hang
        Map<Integer, Integer> allGroupIds = new HashMap<>();
        allGroupIds = mysqlMain.getAllGroupID();
        
        //lay tat ca nhung campaignid va userid lien quan
        Map<Integer, String> CampaignAndUserid = new HashMap<>();
        CampaignAndUserid = mysqlMain.getCampaignAndUseridCPM(currentDate);
        
        //Lay tien va click theo campaign va domain
        //chu y : lay nhung banner cpc 
        Map<String, String> MoneyByCampaign = new HashMap<>();
        MoneyByCampaign = mysql.getMoneyByCampaignIdAndDomainCPM(currentDate);
        
        //lay nhung domain hop le
        List validBanner = new ArrayList();
        validBanner = mysqlMain.getValidDomain();
        /*
            //lay nhung campaign thuoc cpc plus
            List CampaignCPCPlus = new ArrayList();
            CampaignCPCPlus = mysqlMain.getCampaignCPCPlus();

            //lay gia cpcplus doi voi moi domain
            Map<String, Integer> PriceByDomainCPCPlus = new HashMap<>();
            PriceByDomainCPCPlus = mysqlMain.getPriceByDomainCPCPlus();
        */
        
        //get every user
        Set s = allUsers.entrySet();
        Iterator it=s.iterator();
        //tinh xem group la 1 hay 2
        int flagGroup = 0;
        
        while(it.hasNext())
        {
            Map.Entry m =(Map.Entry)it.next();
            //key la userid
            int key=(Integer)m.getKey();
            //value la balance_promotion
            String valueMoneyByUserID = (String)m.getValue();
            String[] arrMoney = new String[3];
            arrMoney = valueMoneyByUserID.split("_");
            
            int balance = Integer.valueOf(arrMoney[0]);
            int promotion = Integer.valueOf(arrMoney[1]);
            int groupid = Integer.valueOf(arrMoney[2]);
            
            //moi userid tim campaignid tuong ung
            if(CampaignAndUserid.containsKey(key))
            {
                //mot userid co the co nhieu campaign
                String campaignIds = CampaignAndUserid.get(key);
                String[] arrCamp = new String[100];
                arrCamp = campaignIds.split(",");
                //lay ra moi campaign
                //countCp = countCp + arrCamp.length;
                for(int i = 0; i< arrCamp.length ; i++)
                {                                        
                    long campaignId = Long.valueOf(arrCamp[i]);
                    //lay moi key cua Map nay
                    //sau do parse key ra de lay domain va campId
                    //so sanh campId o tren va campid da parse
                    //neu bang nhau thi insert du lieu
                    //neu khong thi tiep tuc
                    Set s2 = MoneyByCampaign.entrySet();
                    Iterator it2 = s2.iterator();
                    while(it2.hasNext())
                    {                       
                        Map.Entry m2 =(Map.Entry)it2.next();
                        //key2 la campID_domain
                        String key2=(String)m2.getKey();                        
                        String[] arrData = new String[2];                        
                        arrData = key2.split("_");                        
                        String domain = arrData[1];                        
                        //System.out.println(arrData[1]);
                        try{
                            //if(Long.valueOf(arrData[0]) == campaignId && validBanner.contains(domain)){
                            if(Long.valueOf(arrData[0]) == campaignId){
                                //check xem là nội bộ hay khách hàng
                                //neu la noi bo thi group = 1
                                //neu la khach hang thi = 2
                                if(allGroupIds.containsKey(groupid))
                                {
                                   flagGroup = allGroupIds.get(groupid);
                                }
                                //count ++;
                                //System.out.println("campaignid :" +Integer.valueOf(arrData[0]));
                                //value la money_totalclick
                                String dataByCampaign = (String)m2.getValue();
                                String[] arr = new String[3];
                                arr = dataByCampaign.split("_");

                                int moneyByDomain = Integer.valueOf(arr[0]);
                                int totalclick = Integer.valueOf(arr[1]);
                                int totalview = Integer.valueOf(arr[2]);
                                /*
                                if (CampaignCPCPlus.contains(campaignId))
                                {
                                    System.out.println("campaignid :" +campaignId+"_totalclick:"+totalclick);
                                }*/

                                //neu <= balance thi tinh tai khoan chinh
                                if(moneyByDomain <= balance){
                                    String sqlString = "(" + key + "," + campaignId +",'" + domain + "',CRC32('" + domain +"')," +totalclick+ "," + totalview + "," + moneyByDomain +",0,"+ groupid +","+ flagGroup +",'" + currentDate +"')";
                                     sb.append(sqlString).append(",");
                                }
                                //neu tai khoan chinh < 0 thi chi tinh tai khoan khuyen mai
                                else if(balance <= 0)
                                {
                                    //neu tai khoan khuyen mai >
                                    if(promotion >= moneyByDomain)
                                    {
                                        String sqlString = "(" + key + "," + campaignId +",'" + domain + "',CRC32('" + domain +"')," + totalclick + "," + totalview +"," + 0 +"," + moneyByDomain +","+ groupid +","+ flagGroup +",'" + currentDate +"')";
                                        sb.append(sqlString).append(",");
                                     //neu tai khoan khuyen mai <
                                    }else{
                                        String sqlString = "(" + key + "," + campaignId +",'" + domain + "',CRC32('" + domain +"')," +totalclick + "," + totalview +"," + (moneyByDomain-promotion) +"," + promotion +","+ groupid +","+ flagGroup +",'" + currentDate +"')";
                                        sb.append(sqlString).append(",");
                                    }
                                }
                                //neu > tai khoan chinh va con tai khoan khuyen mai
                                else{
                                    if((balance + promotion) > moneyByDomain)
                                    {
                                        String sqlString = "(" + key + "," + campaignId +",'" + domain + "',CRC32('" + domain +"')," + totalclick + "," + totalview +"," + balance +"," + (moneyByDomain-balance) +","+ groupid +","+ flagGroup +",'" + currentDate +"')";
                                        sb.append(sqlString).append(",");
                                    } else {
                                        String sqlString = "(" + key + "," + campaignId +",'" + domain + "',CRC32('" + domain +"')," + totalclick + "," + totalview +"," + (moneyByDomain-promotion) +"," + (promotion)+","+ groupid +","+ flagGroup +",'" + currentDate +"')";
                                        sb.append(sqlString).append(",");
                                    } 
                                }
                                //Debug.println(dataByCampaign);
                                //break;
                                } else {
                                continue;
                            }
                        }catch (Exception ex){
                            //Debug.println(ex.getMessage());
                        }
                    }                    
                }                
            }

            if(sb.toString().length() > 1000)
            {
                //MysqlDataManagerLV mysqlLV = new MysqlDataManagerLV();
                //xu li cho du lieu cuoi
                String relStr = sb.toString();
                String valInsert = relStr.substring(0, (relStr.length()-1));
                mysql.insertBalanceAndPromotionMoneyCPM(valInsert);
                sb.setLength(0);
            }
        }
        
        if(sb.toString().length() > 0)
        {
            //MysqlDataManagerLV mysqlLV = new MysqlDataManagerLV();
            //xu li cho du lieu cuoi
            String relStr = sb.toString();
            String valInsert = relStr.substring(0, (relStr.length()-1));
            mysql.insertBalanceAndPromotionMoneyCPM(valInsert);
            sb.setLength(0);
        }
        //close connection
        mysql.shutdownConnection();
        mysqlMain.shutdownConnection();
        
        long last_time = System.currentTimeMillis();
        Debug.println("Thoi gian chay livebudget CPM  :" +(last_time-first_time));
    }

    /*
     * Lay thoi gian tu 6h sang ngay hom truoc toi 5h59 sang ngay hom sau
     * Coi la 1 ngay
     */
    public static String handleDate()
    {
        String retDate = "";//2012-07-24
        String date = TimeUtil.getCurrentTimeInStringForLog();//yyyy/MM/dd H:mm:ss

        String[] arrTime        = new String[2];
        String[] firstArrTime   = new String[3];
        String[] secondArrTime  = new String[3];

        arrTime = date.split(" ");
        firstArrTime    = arrTime[1].split(":");
        secondArrTime   = arrTime[0].split("-");
        if(Integer.valueOf(firstArrTime[0]) >= 7 && Integer.valueOf(firstArrTime[0]) <= 23)
        {
            retDate = secondArrTime[0]+"-"+secondArrTime[1]+"-"+secondArrTime[2];
        }
        //init checkDate if trigger from 0h -> 6h
        else if (Integer.valueOf(firstArrTime[0]) >= 0 && Integer.valueOf(firstArrTime[0]) < 7 && TimeUtil.getCurrentTime() >= checkDateDomainDate)
        {
            //Debug.println(date + "_" + TimeUtil.getCurrentTime() + "_" + checkDateDomainDate);
            int day = Integer.valueOf(secondArrTime[2]) - 1;
            if(day < 10){
                retDate = secondArrTime[0]+"-"+secondArrTime[1]+"-"+"0"+String.valueOf(day);
            } else{
                retDate = secondArrTime[0]+"-"+secondArrTime[1]+"-"+String.valueOf(day);
            }
        }
        return retDate;
    }
}
